package main

import (
	"flag"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"mysql_markdown/db/mysql"
	"os"
	"path/filepath"
	"xorm.io/core"
	"time"
)

func main() {
	var dbType, host, port, dbName, user, pwd, outputFilePath string
	flag.StringVar(&dbType, "type", "mysql", "数据库类型，默认mysql")
	flag.StringVar(&host, "h", "127.0.0.1", "数据库主机，默认127.0.0.1")
	flag.StringVar(&dbName, "d", "", "数据库名称")
	flag.StringVar(&port, "P", "3306", "数据库端口，默认3306")
	flag.StringVar(&user, "u", "root", "用户，默认root")
	flag.StringVar(&pwd, "p", "", "用户口令")
	flag.StringVar(&outputFilePath, "o", filepath.Join(os.TempDir(), dbName + ".md"), "markdown输出文件")
	flag.Parse()
	if dbType != "mysql" {
		panic("当前仅支持mysql")
	}
	if len(dbName) == 0 {
		panic("未指定数据库")
	}
	if len(pwd) == 0 {
		panic("未指定用户口令")
	}
	dbEngine := GetEngine(dbType, host, port, dbName, user, pwd)

	mysql.ExportMarkdown(dbEngine, outputFilePath)
}

func GetEngine(dbType, host, port, dbName, user, pwd string) *xorm.Engine {
	//conn string
	conn := user + ":" + pwd + "@tcp(" + host + ":" + port + ")/" + dbName + "?charset=utf8&loc=Asia%2FShanghai&parseTime=true"
	engine, err := xorm.NewEngine(dbType, conn)
	if err != nil {
		panic(err)
	}
	// 打印sql
	loga := xorm.NewSimpleLogger(os.Stdout)
	loga.SetLevel(core.LOG_INFO)
	engine.SetLogger(loga)
	engine.ShowSQL(true)
	//连接生存时间半个小时
	engine.SetConnMaxLifetime(1800 * time.Second)
	return engine
}

